import React, { useEffect, useRef, useState } from "react";
import * as echarts from "echarts";
import { CSSProperties } from "react";

interface LineChartProps {
  initialData?: number[];
}

const LineChart: React.FC<LineChartProps> = ({
  initialData = [5, 20, 36, 10, 10, 20],
}) => {
  const chartRef = useRef<HTMLDivElement | null>(null);
  const [data, setData] = useState<number[]>(initialData);

  useEffect(() => {
    if (chartRef.current) {
      const myChart = echarts.init(chartRef.current);

      myChart.setOption({
        title: {
          text: "ECharts 入门示例",
        },
        tooltip: {},
        xAxis: {
          data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
        },
        yAxis: {},
        series: [
          {
            name: "销量",
            type: "line",
            data: data,
          },
        ],
      });

      return () => {
        myChart.dispose();
      };
    }
  }, [data]);

  const chartStyle: CSSProperties = {
    width: 600,
    height: 400,
  };

  // 示例：动态更新数据
  const updateData = () => {
    setData([
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
    ]);
  };

  return (
    <>
      <button onClick={updateData}>更新数据</button>
      <div ref={chartRef} style={chartStyle}></div>
    </>
  );
};

export default LineChart;
